//
//  剑指Offer58-II左旋转字符串.swift
//  LeetCodeTrain
//
//  Created by rjb on 2021/7/11.
//  Copyright © 2021 rjb. All rights reserved.
//

import Foundation

class SolutionSord58II {
    // 此题的反转。也可以先局部反转，然后。整体反转。这样可以不借助其他空间就可以实现。
    func reverseLeftWords(_ s: String, _ n: Int) -> String {
        var cChars: [Character] = Array(s)
        reverseRange(&cChars, start: 0, end: n - 1)
        reverseRange(&cChars, start: n, end: cChars.count - 1)
        reverseRange(&cChars, start: 0, end: cChars.count - 1)
        return cChars.map {String($0)}.joined()
    }
    
    func reverseRange(_ cChars:inout [Character], start: Int, end: Int) {
        var left = start
        var right = end
        while left < right {
            let tmp = cChars[left]
            cChars[left] = cChars[right]
            cChars[right] = tmp
            left += 1
            right -= 1
        }
    }
    
    static func test() {
        let s = "lrloseumgh"
        let k = 6
        let solution = SolutionSord58II()
        let result = solution.reverseLeftWords(s, k)
        print(result)
    }
}
